<?

$koatuu_table = 'CC_GEO_OBJECT o, CC_GEO_PROPERTY p';

$res = array();
//dbdebug();

if (($id = gccHuuid(param('id'))) || (($id = param('id')) == 'null')) {
	$_crit = ($id == 'null') ? 'parent_id IS NULL' : "parent_id=$id";

	if (sizeof($d = datafetch_array('db_list',
		array('table' => $koatuu_table, 'index' => 'id', 
			'where' => "o.property_id=p.id AND $_crit",
			'order' => 'name',
			'select' => 'o.id id, p.koatuu_name name'
			)))) {
			
		$keys = implode(',', array_keys($d));
		$chi = datafetch_array('db_list', array(
			'table' => 'CC_GEO_OBJECT', 
			'index' => 'parent_id', 
			'where' => "parent_id IN ($keys)",
			'select' => "parent_id, count(parent_id) c",
			'group' => 'parent_id',
			));

		foreach($d as $v) {
			$tmp = array('data' => $v['name'], 'attr' => array('id' => $v['id'], rel => 'folder'));
			if ( $chi[$v['id']]['c'] ) {
				$tmp['state'] = 'closed';
//				$tmp['children'] = array();
			}

			$res[] = $tmp;
		}
	}

	header("Content-Type: application/json; charset=utf-8");

}

print json_encode($res);

exit;
